/*
 * 版权：Copyright PING AN INSURANCE (GROUP) COMPANY OF CHINA ,LTD. All Rights Reserved.
 * 项目名称：cloud-ucp-im-admin
 * 创建人： XIWEICHENG497
 * 创建时间：2018 下午3:10:10
 */
package com.xiweicheng.test.springboot.im.admin.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.xiweicheng.test.springboot.im.admin.entity.security.User;
import com.xiweicheng.test.springboot.im.admin.model.JwtUser;
import com.xiweicheng.test.springboot.im.admin.repository.UserRepository;

/**
 * TODO〈功能描述〉
 * 
 * @author XIWEICHENG497
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            List<GrantedAuthority> authorities = user.getAuthorities().stream().map(
                    auth -> new org.springframework.security.core.authority.SimpleGrantedAuthority(auth.getAuthority()))
                    .collect(Collectors.toList());
            return new JwtUser(user.getUsername(), user.getPassword(), authorities);
        }
    }

}